import './influx.js';
import './dictmap.js';

var metadata = {
  deviceName: '陕西渭南_1-1系统',
  ts: 1758532102894,
};

var msgType = 'Post telemetry';

var msg = {
  site: '陕西渭南',
  siteCode: 'ShXWN',
  workshopNo: '1',
  systemCode: '1-1',
  'WL_ba:wl': 0.79,
  'WL_pp:wl': 1.01,
  'AO3:ah': 0,
  'AO3:at': 0,
};

var siteCode = msg.siteCode;
var workshopNo = msg.workshopNo;
var systemCode = msg.systemCode;

var site = global.dictMap
  ? global.dictMap.siteCode[siteCode]
    ? global.dictMap.siteCode[siteCode].name
    : msg.site
  : msg.site;

var bucket = global.dictMap
  ? global.dictMap.siteCode[siteCode]
    ? global.dictMap.siteCode[siteCode].bucket
    : ''
  : '';

if (!bucket) {
  throw new Error('bucket is empty!!!');
}

var meas = site + '_' + msg.workshopNo + '车间';

// 忽略的key
var ignoreKeys = ['site', 'siteCode', 'workshopNo', 'systemCode'];

var data = [];
// 遍历msg，兼容es5
for (var key in msg) {
  if (msg.hasOwnProperty(key)) {
    if (ignoreKeys.indexOf(key) !== -1) {
      // 如果key在数组中
      continue;
    }
    var value = msg[key];
    var deviceInfo = global.getDeviceInfo(key);
    deviceInfo.measurement = meas;

    // 记录字段
    var field = deviceInfo.field;
    deviceInfo.fields = {};
    deviceInfo.fields[field] = value;
    delete deviceInfo.field;

    // 记录系统缩写
    deviceInfo.tags['_SC'] = siteCode;
    deviceInfo.tags['_WN'] = workshopNo;
    deviceInfo.tags['_SYS'] = systemCode;

    // 记录时间
    deviceInfo.time = metadata.ts;
    // console.log(deviceInfo);
    data.push(deviceInfo);
  }
}

// console.log(global.influx.buildLines(data));

return {
  msg: {
    data: global.influx.buildLines(data),
  },
  metadata: metadata,
  msgType: msgType,
};
